package com.cloudwise.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2021/9/17 11:17
 * @description：字符编码过滤器
 * @modified By：
 * @version: 1.0
 */
@WebFilter(urlPatterns = "/*")
public class AEncodeFilter implements Filter {
    String encode = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        /*System.out.println("EncodeFilter初始化啦");*/


    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       /* System.out.println("EncodeFilter开始工作了");*/
        //默认拦截所有的请求，不放行，尽量不写硬编码 hard code，可以配置
        //从web.xml文件中获取encode的值。
        String encoding = servletRequest.getServletContext().getInitParameter("encoding");
        if (encoding != null) {
            encode = encoding;
        }
        servletRequest.setCharacterEncoding(encode);
        servletResponse.setCharacterEncoding(encode);
        //放行所有
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
     /*   System.out.println("EncodeFilter销毁了！");*/
    }
}
